package com.atguigu.lease.common.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfigruation {
    /**
     * 配置RedisTemplate以支持键值对序列化和反序列化
     * 该方法在Spring框架中定义了一个Bean，用于创建和配置RedisTemplate实例
     * RedisTemplate是Spring Data Redis提供的用于操作Redis数据的模板类，通过它 can perform various operations on Redis data in an object-oriented manner
     *
     * @param redisConnectionFactory Redis连接工厂，用于创建和管理Redis连接
     * @return 配置好的RedisTemplate实例，用于执行Redis操作
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 创建RedisTemplate实例并设置连接工厂
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 定义字符串序列化器和JSON序列化器
        StringRedisSerializer stringRedisSerializer = StringRedisSerializer.UTF_8;
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();

        // 设置键和哈希键的序列化器为字符串序列化器，值和哈希值的序列化器为JSON序列化器
        // 这样可以确保字符串类型的键和哈希键在存储和读取时保持不变，而值则以JSON格式存储和读取
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        // 返回配置好的RedisTemplate实例
        return redisTemplate;
    }
}
